//
//  uploadImgViewController.swift
//  YLH
//
//  Created by qinjiangtao on 2024/1/12.
//

import UIKit
import GKPhotoBrowser
import Alamofire

class uploadImgViewController: QIBaseViewController {
    
    var model = HomeListModel()
    var typeStr = ""
    
    private var imgBtn = UIButton()
    private var selectImg = UIImage()
    // 结果view
    private let resultBgView = UIView()
    private var resultL = YYLabel()
    private var json = JSON()
    private var coverUrl = ""
    private var urlStr = ""
    
    
    private let reuseIdentifier = "text"
    private var grids = [[Grid]]()
    private let tabulationView = TabulationView()
    
    /// 行数
    private let rowCount = 4
    /// 列数
    private let colCount = 4

    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = typeStr
        
       if typeStr == "面容健康" {
            urlStr = "\(BASE_URL)/Check/face"
        } else if typeStr == "居家检测" {
            urlStr = "\(BASE_URL)/Check/room"
        } else if typeStr == "医疗报告" {
            urlStr = "\(BASE_URL)/Check/medical"
        }
        
//        selectImg = UIImage(named: "shaoji") ?? UIImage()
        addUI()
    }
    

  
    private func addUI() {
        self.view.addGradientColor(fromColors: [ColorWithStr("#FFB2B5").cgColor, ColorWithStr("#FCDFE0").cgColor, ColorWithStr("#FFFBFB").cgColor], locationArr: [0, 0.5, 1.0], with: .topToBottom)
        
        let explain = YYLabel().then({
            $0.frame = CGRect(x: 15, y: NAV_HEIGHT + 15, width: SCREEN_WIDTH - 30, height: 70)
            $0.backgroundColor = .clear
            $0.text = "\(model.explain)"
            $0.textContainerInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
            $0.numberOfLines = 0
            $0.textColor = Color333333
            $0.font = SYSFONT(ofSize: 15)
            $0.addRoundedCorners(withRadius: 10)
        })
        view.addSubview(explain)
        
        let imgBgView = UIView()
        imgBgView.frame = CGRect(x: 15, y: explain.bottom + 15, width: SCREEN_WIDTH - 30, height: 222)
        imgBgView.backgroundColor = .clear
        imgBgView.addRoundedCorners(withRadius: 10)
        view.addSubview(imgBgView)
        
        imgBtn = UIButton().then {
            $0.frame = CGRect(x: imgBgView.width / 2 - 75, y: 20, width: 150, height: 150)
            $0.setImage(UIImage(named: "noo"), for: .normal)
            $0.imageView?.contentMode = .scaleAspectFill
            $0.addRoundedCorners(withRadius: 8)
            $0.addTarget(self, action: #selector(imgBtnClick), for: .touchUpInside)
        }
        imgBgView.addSubview(imgBtn)
        
        let titleL1 = UILabel().then({
            $0.frame = CGRect(x: 0, y: imgBtn.bottom + 15, width: imgBgView.width, height: 18)
            $0.text = "请上传图片"
            $0.textAlignment = .center
            $0.textColor = Color333333
            $0.font = SYSFONT(ofSize: 13)
        })
        imgBgView.addSubview(titleL1)
        
        let photoBtn = UIButton().then {
            $0.frame = CGRect(x: 15, y: imgBgView.bottom + 20, width: SCREEN_WIDTH / 2 - 25, height: 45)
            $0.backgroundColor = ColorWithStr("#FFE4E7")
            $0.titleLabel?.font = SYSFONT(ofSize: 13)
            $0.setTitle("选择图片/手机拍摄", for: .normal)
            $0.setTitleColor(MainColor, for: .normal)
            $0.addRoundedCorners(withRadius: 8)
            $0.addBorder(withWidth: 1, borderColor: MainColor)
            $0.addTarget(self, action: #selector(photoBtnClick), for: .touchUpInside)
        }
        view.addSubview(photoBtn)
        
        let uploadBtn = UIButton().then {
            $0.frame = CGRect(x: SCREEN_WIDTH / 2 + 10, y: photoBtn.top, width: photoBtn.width, height: photoBtn.height)
            $0.backgroundColor = MainColor
            $0.titleLabel?.font = SYSFONT(ofSize: 13)
            $0.setTitle("上传", for: .normal)
            $0.setTitleColor(.white, for: .normal)
            $0.addRoundedCorners(withRadius: 8)
            $0.addTarget(self, action: #selector(uploadBtnClick), for: .touchUpInside)
        }
        view.addSubview(uploadBtn)
        
        resultBgView.frame = CGRect(x: 15, y: photoBtn.bottom + 20, width: SCREEN_WIDTH - 30, height: 222)
        resultBgView.backgroundColor = .clear
        resultBgView.addRoundedCorners(withRadius: 10)
        view.addSubview(resultBgView)
        
        let titleL2 = UILabel().then({
            $0.frame = CGRect(x: 15, y: 15, width: 100, height: 22)
            $0.text = "结果"
            $0.textColor = Color333333
            $0.font = SYSFONT(ofSize: 16)
        })
        resultBgView.addSubview(titleL2)
        
        resultL = YYLabel().then({
            $0.frame = CGRect(x: 15, y: titleL2.bottom + 10, width: resultBgView.width - 30, height: 180)
            $0.text = "暂无结果"
            $0.textVerticalAlignment = .top
            $0.numberOfLines = 0
            $0.textColor = Color666666
            $0.font = SYSFONT(ofSize: 14)
        })
        resultBgView.addSubview(resultL)
        
        let contactBtn = UIButton().then {
            $0.frame = CGRect(x: 20, y: SCREEN_HEIGHT - 70, width: SCREEN_WIDTH - 40, height: 44)
            $0.backgroundColor = MainColor
            $0.titleLabel?.font = SYSFONT(ofSize: 13)
            $0.setTitle("联系专家", for: .normal)
            $0.setTitleColor(.white, for: .normal)
            $0.addRoundedCorners(withRadius: 8)
            $0.addTarget(self, action: #selector(contactBtnClick), for: .touchUpInside)
        }
        view.addSubview(contactBtn)
        
    }
    
    
    @objc private func imgBtnClick() {
        guard selectImg.size.width > 0 else {
            photoBtnClick()
            return
        }
        
        var photos = [GKPhoto]()
        let photo = GKPhoto()
        photo.image = imgBtn.imageView?.image!
        photos.append(photo)
        
        
        let browser = GKPhotoBrowser(photos: photos, currentIndex: 0)
        browser.showStyle = .none
        browser.show(fromVC: self)
        
    }
    @objc private func photoBtnClick() {
        let alertCtl = UIAlertController(title: "选项", message: nil, preferredStyle: .actionSheet)
        alertCtl.addAction(UIAlertAction(title: "拍照", style: .default, handler: { (_) in
            let imagePickerCtl = UIImagePickerController()
            imagePickerCtl.delegate = self
            imagePickerCtl.allowsEditing = true
            imagePickerCtl.sourceType = .camera
            self.present(imagePickerCtl, animated: true)
        }))
        alertCtl.addAction(UIAlertAction(title: "从手机相册选择", style: .default, handler: { (_) in
            let imagePickerCtl = UIImagePickerController()
            imagePickerCtl.delegate = self
            imagePickerCtl.allowsEditing = true
            imagePickerCtl.sourceType = .savedPhotosAlbum
            self.present(imagePickerCtl, animated: true)
        }))
        alertCtl.addAction(UIAlertAction(title: "取消", style: .cancel, handler: { (_) in
            
        }))
        self.present(alertCtl, animated: true)
    }
    
    @objc private func uploadBtnClick() {
        updateImage()
    }
    
    @objc private func contactBtnClick() {
        let alertCtl = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
        alertCtl.addAction(UIAlertAction(title: "AI助手", style: .default, handler: { (_) in
            let ctl = AnswerListViewController()
            self.navigationController?.pushViewController(ctl, animated: true)
        }))
        alertCtl.addAction(UIAlertAction(title: "临床专家", style: .default, handler: { (_) in
            
        }))
        alertCtl.addAction(UIAlertAction(title: "取消", style: .cancel, handler: { (_) in
            
        }))
        self.present(alertCtl, animated: true)
    }

}



extension uploadImgViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        let image: UIImage = info[UIImagePickerController.InfoKey.editedImage] as! UIImage
        imgBtn.setImage(image, for: .normal)
        selectImg = image
        picker.dismiss(animated: true)
    }
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        self.dismiss(animated: true)
    }
    
    private func updateImage() {
        guard selectImg.size.width > 0 && selectImg.size.height > 0 else {
            ShowHUD(str: "请选择图片")
            return
        }
        
        HUD.flash(.labeledProgress(title: "", subtitle: "图片分析中..."), delay: 5.0)
        let data = selectImg.jpegData(compressionQuality: 0.4) ?? Data()
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyyMMddHHmmss"
        let dateString = formatter.string(from: Date())
        let fileName = "iOS-\(dateString).jpeg"
        
        let bearer = Defaults[\.bearer]
        let headers: HTTPHeaders = [
            "Authorization": bearer
        ]
        
        AF.upload(multipartFormData: { multipartFormData in
            
            multipartFormData.append(data, withName: "image", fileName: fileName, mimeType: "image/jpeg")
            
        }, to: urlStr, method: .post, headers: headers)
        .uploadProgress { progress in
            print("---------\(progress.fractionCompleted)")
        }
        .response { resp in
            HUD.hide()
            switch resp.result {
            case let .success(data):
                guard data != nil else {
                    ShowHUD(str: "返回数据为空")
                    return
                }
                
                let json = JSON(data!)
                print(json)
                self.json = json
                let model = json.dictionaryObject?.kj.model(QIBaseModel.self) ?? QIBaseModel()
                guard model.code == 1 else {
                    ShowHUD(str: model.msg)
                    return
                }
                if self.typeStr == "面容健康" {
                    let dict: [String: Any] = json["data"].rawValue as! [String : Any]
                    self.generateData(dict: dict)
                } else if self.typeStr == "医疗报告" {
                    self.resultL.text = "图片上传成功"
                } else if self.typeStr == "居家检测" {
                    self.resultL.text = "图片上传成功"
                }
            case let .failure(err):
                ShowHUD(str: "\(self.urlStr)调用出错")
                print(err)
            }
        }
    }
    
}

// 其他接口处理
extension uploadImgViewController {
    
    /// 面容扫描
    private func facialScanningData(predict: String) {
        QINetworkManager.requestJson(urlStr: "/Check/face", parameters: ["image": coverUrl, "predict": predict]) { json in
            print(json)
        }
    }
    
}


// 面容健康
extension uploadImgViewController: TabulationViewDataSource {
    
    func generateData(dict: [String: Any]) {
        for row in 0..<rowCount {
            var rowGrids = [Grid]()
            for col in 0..<colCount {
                var text = ""
                var textColor = Color333333
                if col == 0 {
                    if row == 0 {
                        text = "脸龄"
                    } else if row == 1 {
                        text = "左眼形"
                    } else if row == 2 {
                        text = "右眼形"
                    } else if row == 3 {
                        text = "鼻型"
                    }
//                    textColor = UIColor(red: 241.0 / 255.0, green: 171.0 / 255.0, blue: 114.0 / 255.0, alpha: 1)
                    textColor = .orange
                } else if col == 1{
                    if row == 0 {
                        text = "\(dict["face_age"] ?? "")"
                    } else if row == 1 {
                        text = "\(dict["left_eye_name"] ?? "")"
                    } else if row == 2 {
                        text = "\(dict["right_eye_name"] ?? "")"
                    } else if row == 3 {
                        text = "\(dict["nose_name"] ?? "")"
                    }
                } else if col == 2{
                    if row == 0 {
                        text = "脸型"
                    } else if row == 1 {
                        text = "左眉形"
                    } else if row == 2 {
                        text = "右眉形"
                    } else if row == 3 {
                        text = "唇型"
                    }
                    textColor = .orange
                } else if col == 3{
                    if row == 0 {
                        text = "\(dict["face_name"] ?? "")"
                    } else if row == 1 {
                        text = "\(dict["left_eyebrow_name"] ?? "")"
                    } else if row == 2 {
                        text = "\(dict["right_eyebrow_name"] ?? "")"
                    } else if row == 3 {
                        text = "\(dict["mouth_name"] ?? "")"
                    }
                }
                
                let grid = Grid(content: text)
                grid.textColor = textColor
                rowGrids.append(grid)
            }
            grids.append(rowGrids)
        }
        addMianRongJianKangUI()
        tabulationView.reloadData()
    }
    
    private func addMianRongJianKangUI() {
        
        tabulationView.frame = CGRect(x: 0, y:40, width: Int(resultBgView.width), height: 40 * rowCount + 5)
        tabulationView.backgroundColor = UIColor(red: 170/255, green: 200/255, blue: 230/255, alpha: 1)
        tabulationView.register(TextTabulationViewCell.self, forCellReuseIdentifier: reuseIdentifier)
        tabulationView.dataSource = self
        resultBgView.addSubview(tabulationView)
        
    }
    
    func numberOfRows(in tabulationView: TabulationView) -> Int {
        return rowCount
    }
    
    func numberOfCols(in tabulationView: TabulationView) -> Int {
        return colCount
    }
    
    //列宽
    func tabulationView(_ tabulationView: TabulationView, lengthForCol col: Int) -> CGFloat {
        return resultBgView.width / 4 - 1
    }
    
    func tabulationView(_ tabulationView: TabulationView, cellForIndexPath indexPath: TabIndexPath) -> TabulationViewCell? {
        
        guard let cell = tabulationView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath) as? TextTabulationViewCell else {
            return nil
        }
        let grid = grids[indexPath.row][indexPath.col]
        cell.loadGrid(grid)
        return cell
    }
}
